<?php

namespace plugin\thinkphp;

use ExAdmin\ui\plugin\Plugin;
use ExAdmin\ui\component\form\Form;
use plugin\thinkphp\exception\ExceptionHandler;
use plugin\thinkphp\filesystem\Filesystem;
use plugin\thinkphp\middleware\AuthMiddleware;
use plugin\thinkphp\middleware\LoadLangPack;
use plugin\thinkphp\middleware\Permission;
use plugin\thinkphp\traits\DataPermissions;
use think\facade\Db;
use think\facade\Route;
use think\Model;

class ServiceProvider extends Plugin
{
    /**
     * 注册服务
     *
     */
    public function register()
    {
        include_once 'helpers.php';
        //上传初始化
        Admin::uploadInit();

        //注册中间件
        $middleware = config('middleware');
        $middleware['alias']['admin'] = [
            AuthMiddleware::class,
            LoadLangPack::class,
            Permission::class
        ];
        config($middleware, 'middleware');

        //filesystem
        app()->bind('filesystem',Filesystem::class);

        //模型数据权限
        Model::maker(function ($model){
            $reflectionClass = new \ReflectionClass($model);
            $property = $reflectionClass->getProperty('globalScope');
            $property->setAccessible(true);
            $globalScope = $property->getValue($model);
            $globalScope = array_merge($globalScope,['dataAuth']);
            $property->setValue($model,$globalScope);
        });
        /**
         * @var $loader \Composer\Autoload\ClassLoader
         */
        $loader = include dirname(__DIR__, 2)  . '/vendor/autoload.php';
        //判断安装多应用
        $prefix = plugin()->thinkphp->config('route.prefix');
        if(array_key_exists('think\\app\\',$loader->getPrefixesPsr4()) && is_dir(app_path($prefix))){
            $prefix = '';
        }
        $group = Route::group($prefix, function () {
            Route::get('/', function () {
                $content = file_get_contents(public_path('exadmin') . '/index.html');
                return str_replace(
                    [
                        '{{Ex-Admin}}',
                        '{{Ex-Admin-App-Name}}',
                    ],
                    [
                        admin_sysconf('web_name'),
                        plugin()->thinkphp->config('route.prefix'),
                    ],
                    $content);
            });
        });
        if(plugin()->thinkphp->config('route.domain')){
            $group->domain(plugin()->thinkphp->config('route.domain'));
        }
        $appName = plugin()->thinkphp->config('route.prefix');
        if (input('App-Name') == $appName || request()->header('App-Name') == $appName) {
            admin_config($this->config(), 'admin');
            admin_config($this->config('ui'), 'ui');
            app()->bind('think\exception\Handle',ExceptionHandler::class);
        }
        Route::any('ex-admin/<class>/<function>', function ($class, $function) {
            return \ExAdmin\ui\Route::dispatch($class, $function);
        })->middleware('admin');
    }

    /**
     * 设置
     * @return Form
     */
    public function setting(): Form
    {
        $form = Form::create(__DIR__ . '/config.php');
        $form->title('配置');
        return $form;
    }

    /**
     * 安装
     * @return mixed
     */
    public function install()
    {
        \think\facade\Console::call('admin:migrate:run');
        \think\facade\Console::call('admin:seed:run');
    }
    /**
     * 更新
     * @param string $old_version 旧版本
     * @param string $version 更新版本
     * @return mixed
     */
    public function update(string $old_version,string $version)
    {
        if(version_compare($old_version,'1.1.2') <= 0){
            $this->install();
            //创建菜单
            $table = plugin()->thinkphp->config('database.menu_table');
            $create_time = date('Y-m-d H:i:s');
            Db::table($table)->insertAll([
                [
                    'pid' => 6,
                    'name' => 'department_manage',
                    'icon' => 'far fa-circle',
                    'url' => 'ex-admin/plugin-thinkphp-controller-DepartmentController/index',
                    'sort' => 8,
                    'create_time' => $create_time
                ],
                [
                    'pid' => 6,
                    'name' => 'post_manage',
                    'icon' => 'far fa-circle',
                    'url' => 'ex-admin/plugin-thinkphp-controller-PostController/index',
                    'sort' => 9,
                    'create_time' => $create_time
                ]
            ]);
        }
    }
    /**
     * 卸载
     * @return mixed
     */
    public function uninstall()
    {

    }
}
